// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import BaseView from "../base/BaseView";
import StockListComponent from "../base/components/StockListComponent";
import FileModule from "../module/FileModule";
import LogModule from "../module/LogModule";
import MatchModule from "../module/MatchModule";
import SeptkapaModule from "../module/SeptkapaModule";
import TimeModule from "../module/TimeModule";
import DropList from "./items/DropList";

const {ccclass, property} = cc._decorator;

const StockDaysRankConfigKey = 'stock_days_rank_config';

var DropConfig = [
    {
        key: 'tradeDayCnt',
        data: ['1', '2', '3', '5', '8', '10', '15', '20', '30', '50', '80', '100', '120'],
        value: [1, 2, 3, 5, 8, 10, 15, 20, 30, 50, 80, 100, 120],
        defaultIndex: 0,
    },
    {   //
        key: 'onlyZhuban',
        data: ['是', '否'],
        value: [false, true],
        defaultIndex: 1,
    },
    {   //
        key: 'removeSt',
        data: ['是', '否'],
        value: [true, false],
        defaultIndex: 1,
    },
    {   //
        key: 'upRank',
        data: ['升序', '降序'],
        value: [true, false],
        defaultIndex: 0,
    },
    {   //
        key: 'total',
        data: ['10', '15', '20', '50', '100', '150', '200', '300', '500', '全部'],
        value: [10, 15, 20, 50, 100, 150, 200, 300, 500, 10000],
        defaultIndex: 0,
    },
];

@ccclass
export default class StockDaysRankViews extends BaseView {

    // LIFE-CYCLE CALLBACKS:
    @property([DropList])
    dropLists: DropList[] = [];

    @property(cc.Prefab)
    stockListPrefab: cc.Prefab = null;

    @property(cc.Node)
    stockListLayer: cc.Node = null;

    stockListComp: StockListComponent = null;

    _searchStocks: any = [];

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        let lastSearchConfig = SeptkapaModule.getInstance().getValue(StockDaysRankConfigKey);

        for (let index = 0; index < this.dropLists.length; index++) {
            const drop = this.dropLists[index];
            let config = DropConfig[index];
            let selectIndex = config.defaultIndex;
            if (lastSearchConfig && lastSearchConfig[config.key] !== undefined) {
                selectIndex = lastSearchConfig[config.key];
            }
            drop.setData(config.data, selectIndex);
        }

        let node = cc.instantiate(this.stockListPrefab);
        this.stockListLayer.addChild(node);
        this.stockListComp = node.getComponent(StockListComponent);
    }

    start () {

    }

    protected onEnable(): void {
        cc.director.on('SelectStockEvent', this.onSelectStockEvent, this);
    }

    protected onDisable(): void {
        cc.director.off('SelectStockEvent', this.onSelectStockEvent, this);
    }

    onSelectStockEvent (selectIndex) {
        this.createDialog(BaseView.Views.StockInfoView, {stocks: this._searchStocks, selectIndex: selectIndex} );
    }

    async onBtnSearch () {
        let condition = {};
        let searchConfig = {};
        for (let index = 0; index < this.dropLists.length; index++) {
            const drop = this.dropLists[index];
            let config = DropConfig[index];
            let selectIndex = drop.getSelectIndex();
            condition[config.key] = config.value[selectIndex];
            searchConfig[config.key] = selectIndex;
        }
        SeptkapaModule.getInstance().setValue(StockDaysRankConfigKey, searchConfig);
		LogModule.log('开始搜索股票...');
		let match = new MatchModule();
        let stocks = await match.matchStockDaysRank(condition);
        this.setStockData(stocks);
        this._searchStocks = stocks;
    }

    onBtnSave () {
        if (this._searchStocks.length == 0) {
            this.showToast("列表为空，导出失败");
            return;
        }
        let totalStr = '';
        for (let index = 0; index < this._searchStocks.length; index++) {
            const item = this._searchStocks[index];
            let market = item.market;
            let str = `${item.ts_code}  ${item.name}  市值${Math.ceil(market.total_mv / 10000)}亿  市盈率ttm:${market.pe_ttm}  市净率${market.pb}\n`;
            totalStr += str;
        }

        FileModule.saveStringAsync('stock_days_rank' + TimeModule.getInstance().strToday(), totalStr, 10);
    }

    //分析板块
    onBtnAnalyse () {
        if (this._searchStocks.length == 0) {
            this.showToast("列表为空");
            return;
        }

        let params = {
            stocks: this._searchStocks,
            type: 'upLimitCount',
        };

        this.createDialog(BaseView.Views.AnalyseStocksView, params);
    }

    setStockData (stocks: any) {
        this.stockListComp.setData(stocks);
        this._searchStocks = stocks;
        LogModule.log('找到股票数量:' + stocks.length);
    }

    // update (dt) {}
}
